package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
)

//实体列表
type DbEntityListData struct {
    Class1 int `db:"Fclass1" json:"class1"`
    Class2 int `db:"Fclass2" json:"class2"`
    EntityName string `db:"Fname" json:"name"`
}

type JsonEntityListData struct {
    ClassName    string  `json:"class_name"`
    EntityName []string  `json:"entity_name"`
}

type DisplayEntityListCgi struct {
	Common.CgiBase
	DbEntity []DbEntityListData
	JsonEntity []JsonEntityListData
}

func (cgi *DisplayEntityListCgi)quertEntityList() (bool) {
	sql := "select Fname,Fclass1,Fclass2 from db_entity_set_data order by Fclass1,Fclass2,rand();"
	err := Databases.Db.Select(&cgi.DbEntity, sql)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return false
	}
    return true
}

func (cgi *DisplayEntityListCgi)transformEntity() (string){
	current_class := -1
	current_pos := -1
	same := 0
	for i := 0; i < len(cgi.DbEntity); i++ {
		if cgi.DbEntity[i].Class2 != current_class {
			current_class = cgi.DbEntity[i].Class2
			fmt.Println("class id, ",current_class)
			var json_entity JsonEntityListData
			json_entity.ClassName = Common.GetEntityNameByClass(current_class)
			fmt.Println("class name, ",json_entity.ClassName)
			cgi.JsonEntity = append(cgi.JsonEntity, json_entity)
			current_pos = current_pos + 1
			cgi.JsonEntity[current_pos].EntityName = append(cgi.JsonEntity[current_pos].EntityName, cgi.DbEntity[i].EntityName)
			same = 0
		} else {
			same = same + 1
			if same < 200 {
				cgi.JsonEntity[current_pos].EntityName = append(cgi.JsonEntity[current_pos].EntityName, cgi.DbEntity[i].EntityName)
			}
		}
	}

    str, _ := json.Marshal(cgi.JsonEntity)
    str_res := string(str)
    return str_res
}

func (cgi *DisplayEntityListCgi)processParam(c *gin.Context) {
}

func DisplayEntityList(c *gin.Context) {
	var cgi DisplayEntityListCgi
	cgi.Init(c)
	cgi.processParam(c)

	res := cgi.quertEntityList()
	if (!res) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "query fail",
	        "data": "{}",
	    })
	    return
	}

	json_res := cgi.transformEntity()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

